<template>
  <div class="userRegister">
    <h1 class="tc">注册</h1>
    <el-form :model="codeForm" :rules="codeFormRules" ref="codeFormRef" class="code_form" >
      <el-form-item prop="phone" class="must-item_P p_r">
        <el-input placeholder="手机号" v-model="codeForm.phone">
          <div slot="prefix" class="phone_icon"></div>
        </el-input>
        <el-button class="code_btns"  type="text" @click="getVCode('codeFormRef')" :disabled="btnIsDisabled">{{VCodeText}}</el-button>
      </el-form-item>
      <el-form-item prop="code" class="must-item_P p_r ">
        <!-- <el-input placeholder="验证码" v-model="codeForm.code" class="code_input" @keyup.enter.native="codeLogin('codeFormRef')">
          <div slot="prefix" class="code_icon"></div>
        </el-input> -->
        <sixCaptchaInput ref="sixCaptchaInput" :code.sync="codeForm.code" @updateCode='updateCode' />
      </el-form-item>
      <el-form-item prop="name" class="must-item_P p_r">
        <el-input placeholder="姓名" v-model="codeForm.name">
          <div slot="prefix" class="inviteCode_icon"></div>
        </el-input>
      </el-form-item>
      <el-form-item prop="id_card" class="must-item_P p_r">
        <el-input placeholder="身份证号" v-model="codeForm.id_card">
          <div slot="prefix" class="inviteCode_icon"></div>
        </el-input>
      </el-form-item>
      <el-form-item prop="inviteCode">
        <el-input placeholder="邀请码（非必填）" v-model.number="codeForm.inviteCode" :disabled="has_code">
          <div slot="prefix" class="inviteCode_icon"></div>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="agreement clearfloat">
      <el-checkbox  v-model="isRead"></el-checkbox>
      <span>我已阅读且同意</span>
      <span class="btns" @click="agreement"><span>服务条款及</span><span>隐私协议</span></span>
      <!-- <el-checkbox class="ml10" v-model="isRead"></el-checkbox>
      <span>我已阅读且同意</span>
      <span class="btns" @click="agreement"><span class="decoration">服务条款</span> <i>和</i>&nbsp;<span class="decoration">隐私协议</span></span> -->
      <el-button type="text" class="fr registered" @click="$router.push('/login?type=2')">已有账号</el-button>
    </div>
    <el-button type="primary" @click="register('codeFormRef')" class="userRegister-btns" :disabled="!isRead" v-no-more-click:3000>注册</el-button>

    <agreement ref="agreement"></agreement>
  </div>
</template>

<script>
import agreement from './components/agreement'
import sixCaptchaInput from '~/components/sixCaptcha-input'
export default {
  components: {
    agreement,
    sixCaptchaInput
  },
  data () {
    var Validateid_card = function(rule, value, callback) {
      if (value === "" || value == undefined || value == null) {
        callback(new Error("请输入身份证号"));
      } else {
        if (!(/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(value))) {
          callback(new Error("请输入正确的身份证号"));
        } else {
          callback();
        }
      }
    }
    var validatePhone = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('请输正确的手机号'));
      } else {
        callback();
      }
    }
    var ValidateinviteCode = (rule, value, callback) => {
      if (value) {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入正确的邀请码格式'))
        } else {
          callback()
        }
        
      } else {
        callback()
      }
    }
    return {
      codeForm: {
        phone: '',
        code: '',
        inviteCode: '',
        id_card:'',
        name:''
      },
      codeFormRules: {
        name: [
          { required: true,  message: "请输入姓名", trigger: 'change' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'change' }
        ],
        code: [
          { required: true,  message: "请输入验证码", trigger: 'change' }
        ],
        inviteCode: [
          { required: true, validator: ValidateinviteCode }
          
        ],
        id_card: [
          { required: true, validator: Validateid_card }
          
        ],
      },
      isRead: true,
      VCodeText: '发送验证码',
      btnIsDisabled: false,
      has_code: false,
    }
  },
  created () {
		if (this.$route.query.code) {
				this.codeForm.inviteCode = this.$route.query.code
				this.has_code = true
			}
		},
  methods: {
    register (formName) {
      this.$refs[formName].validate((valid) => { 
        if (valid) {
          let params = {
						code: this.codeForm.code,
            phone: this.codeForm.phone,
            name: this.codeForm.name,
            id_card: this.codeForm.id_card,
					}
          if (this.codeForm.inviteCode != '') {
            params.invitation_code = this.codeForm.inviteCode
          }
          this.registerPost(params)
        } else {
          return false
        }
      })
    },
    registerPost (params) {
      this.$axios
        .post("/api/consumer/register", params)
        .then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: "注册成功！",
              type: "success"
            });
            this.$router.push({
              name: "index-login",
              params: {
                phone: this.codeForm.phone
              },
              query: {
                type: 2
              }
            })
          } else {
            this.$alert(res.data.message, '提示', {
              confirmButtonText: '确定',
              center: true,
              type: 'warning',
              callback: action => {
              }
            })
          }
        })
    },
    // 获取验证码
    getVCode(formName) {
      this.$refs[formName].validateField('phone', valid => {
        if(!valid) {
          if (this.btnIsDisabled) {
          } else {
            this.getVCodeRequest()
          }
        } else {
          return false
        }
      })
    },
    getVCodeRequest () {
      let that = this;
      let params = {
        phone: this.codeForm.phone,
        type: 1,
        reg_role:5
      }
      that.$axios.post("/api/captcha",params).then(res => {
        if (res.data.code == 200) {
          that.$message({
            message: "验证码发送成功！",
            type: "success"
          })
          let num = 60;
          that.btnIsDisabled = true;
          let timer = setInterval(function() {
            that.VCodeText = num + "秒后可重新发送";
            num -= 1;
            if (num < 0) {
              that.VCodeText = "发送验证码";
              that.btnIsDisabled = false;
              clearInterval(timer);
            }
          }, 1000);
        } else {
          if (res.data.code == 400) {
            that.$message({
              message: res.data.message,
              type: "error"
            })

          } else {
            that.$message({
              message: "验证码发送失败！",
              type: "error"
            })
          }
        }
      })
    },
    // 打开协议
    agreement() {
      this.$refs['agreement'].isShow = true
    },
    updateCode(val) {
      this.codeForm.code = val
    }
  }
}
</script>

<style lang='less'>
  .userRegister {
    width:549px;
    padding: 0 15px 15px;
    // height:590px;
    background:rgba(255,255,255,1);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    h1 {
      font-size:20px;
      font-weight: 400;
      color:rgba(36,157,255,1);
      // margin-top: 30px;
    }
    .code_form {
      width: 390px;
      margin: 0px auto 10px;

      .el-form-item {
        // margin-bottom: 30px;
        position: relative;
        
      }
      .el-input {
        .el-input__inner {
          padding-left: 58px;
        }
        .el-input__prefix {
          left: 20px;
        }
      }
      .el-form-item:last-child {
        margin-bottom: 10px;
        .el-form-item__error {
          padding-top: 1px;
        }
      }
            
      .code_btns {
        position: absolute;
        right: 18px;
        bottom: 0px;
      }
      .phone_icon {
        width:16px;
        height:26px;
        background:url('../../assets/img/图标.png') no-repeat;
        background-position:-371px -419px;
        margin-top: 6px;
      }
      .code_icon {
        width:27px;
        height:17px;
        background:url('../../assets/img/图标.png') no-repeat;
        background-position:-399px -398px;
        margin-top: 10px;
      }
      .inviteCode_icon {
        width:24px;
        height:25px;
        background:url('../../assets/img/图标.png') no-repeat;
        background-position:-402px -435px;
        margin-top: 7px;
      }
    }
    
    .agreement {
      width: 390px;
      margin: 0 auto;
      font-size:12px;
      color:rgba(36,157,255,1);
      i {
        font-style:normal;
        text-decoration:none; 
      }

      .decoration {
        border-bottom: 1px dashed rgba(36,157,255,1);
      }
      .btns {
        cursor: pointer;
      }

      .registered {
        padding: 0;
        font-size: 12px;
        line-height: normal;
      }

    }

    &-btns {
      width: 390px;
      margin: 30px auto 0;
      display: block;
    }
  }
</style>